package cn.edu.szu;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;

public class KeyGeneration {

    // 公钥和私钥
    private BigInteger n, d, e;

    public KeyGeneration() {
        // 随机数生成器
        Random random = new SecureRandom();

        // 生成p和q两个大质数
        BigInteger p = BigInteger.probablePrime(512, random);
        BigInteger q = BigInteger.probablePrime(512, random);

        // 计算pq乘积为n
        n = p.multiply(q);
        assert n.bitLength() == 1024;

        // n的欧拉函数
        BigInteger totient = p.subtract(BigInteger.ONE).multiply(
                q.subtract(BigInteger.ONE));

        // 公钥e，一般认为65537是比较合适的
        e = BigInteger.valueOf(65537);

        // 私钥d，算e对于欧拉函数(n)的模反元素
        d = e.modInverse(totient);

    }

    public BigInteger getN() {
        return n;
    }

    public BigInteger getD() {
        return d;
    }

    public BigInteger getE() {
        return e;
    }

}
